let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
let utils = require('../utils/utils')

// 查询 maoyuan 根据roldId获取permissions
router.get('/', async function(req, res, next) {
    let result = {}
    try {
        let sqlWhere = 'where 1=1'
        let roleId = utils.getQueryValue(req.query.roleId)
        sqlWhere += (roleId==''?'':' AND roleId='+roleId)
        result.data = await mysqlHelper.query('select roleId,type,permissionId from sys_role_permission '+sqlWhere)
        result.code = 200;
        result.success = true
    } catch (err) {
        result.code=400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 新增
router.post('/', async function(req, res, next) {
    let result = {}
    try {
        let sqlStr = "insert into sys_permissions(menuId,name,orderInList) values ('" + req.body.menuId + "','" + req.body.name + "'," + req.body.orderInList + ")"
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 修改
router.put('/', async function(req, res, next) {
    let result = {}
    try {
        let sqlStr = "update sys_permissions set name='" + req.body.name + "',orderInList=" + req.body.orderInList + " where id=" + req.body.id
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 删除
router.delete('/', async function(req, res, next) {
    console.log(req)
    let result = {}
    try {
        await mysqlHelper.query('delete from sys_role_permissions where permissionId=' + req.body.id)
        result.data = await mysqlHelper.query('delete from sys_permissions where id=' + req.body.id)
        console.log(result.data)
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

module.exports = router
